<?php


namespace core\lib;

use \Core\Lib\Config;

/**
 * Class Model
 * @package core\lib
 */
class Model
{
    protected $pdo = null;
    private $charset = 'utf8';

    public $table = '';

    public function __construct()
    {
        $database = Config::all('database');
        //p($database);
        $dsn = 'mysql:host=' . $database['default']['host'] . ';dbname=' . $database['default']['db'];
        $user = $database['default']['user'];
        $pwd = $database['default']['pwd'];
        $this->connect($dsn, $user, $pwd);
    }

    private function connect($dsn, $user, $pwd)
    {
        if (!$this->pdo) {
            $options = array(
                \PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES ' . $this->charset,
            );
            $options = [
                \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,//设置错误模式
                \PDO::ATTR_CASE => \PDO::CASE_NATURAL,//设置数据库字段保持不变
                \PDO::ATTR_EMULATE_PREPARES => TRUE,//启用pdo模拟功能
                \PDO::ATTR_PERSISTENT => TRUE//启用持久性连接
            ];
            try {
                $this->pdo = new \PDO($dsn, $user, $pwd, $options);
            } catch (\PDOException $e) {
                die($e->getMessage());
            }
        }
    }

    public function getAll()
    {
        $sql = "select * from {$this->table}";
        $ret = $this->pdo->query($sql);
        $ret->setFetchMode(\PDO::FETCH_ASSOC);
        return $ret->fetchAll();
    }

    public function getById($id, $field='*')
    {
        $sql = "select {$field} from {$this->table} where id={$id} limit 1";
        $ret = $this->pdo->query($sql);
        $ret->setFetchMode(\PDO::FETCH_ASSOC);
        return $ret->fetch();
    }

    public function decrById($id, $field, $num=1)
    {
        $sql = "update {$this->table} set {$field}={$field}-{$num} where id={$id}";
        $ret = $this->pdo->query($sql);
        $ret->setFetchMode(\PDO::FETCH_ASSOC);
        return $ret->fetch();
    }

    //关闭PDO链接
    public function close()
    {
        return $this->pdo = null;
    }
}